package com.sunlei.webtest.quickstart;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: sun
 * @Description:
 * @Data: create in 21:16 2018/11/21
 * @Modfied by:
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

        System.out.println("-----strat-----");
        /** 1.创建一个connectionFactory */
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        /** 2.通过连接工厂创建连接 */
        Connection connection =  connectionFactory.newConnection();
        /** 3.通过connection创建channel*/
        Channel channel = connection.createChannel();
        /** 4.创建一个队列*/
        String queueName = "test";
        channel.queueDeclare(queueName,true,false,false,null);
        /** 5.创建消费者*/
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        /** 6.设置channel*/
        channel.basicConsume(queueName,true,queueingConsumer);
        /** 7.获取消息*/
        while (true){
            Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("[获取消息]:"+msg);
        }
        /** 5.记得记得关闭连接*/
//        channel.close();
//        connection.close();

    }

}
